﻿using log4net;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using WHLRDF.Log;

namespace WHLRDF.Extensions.Filter
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        readonly IHostingEnvironment _env;//环境变量
        public GlobalExceptionFilter(ILoggerFactory loggerFactory, IHostingEnvironment env)
        {
        
            _env = env;
        }

        public void OnException(ExceptionContext context)
        {
            var controller = context.ActionDescriptor;
          
            #region 记录到内置日志

            #endregion
            if (_env.IsDevelopment())
            {
                LogHelper.Error(context.Exception);
                //var JsonMessage = new ErrorResponse("未知错误,请重试");
                //JsonMessage.DeveloperMessage = context.Exception;
                //context.Result = new ApplicationErrorResult(JsonMessage);
                //context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                //context.ExceptionHandled = true;
            }
            else
            {
                LogHelper.Error(context.Exception);
                context.ExceptionHandled = true;
                context.Result = new RedirectResult("/home/Error");
            }
        }
    }

}
